#include <string.h>
#include <desc.h>
#include <cpu.h>
#include <io.h>
#include <irq.h>
#include <screen.h>
#include <vsprintf.h>
#include <timer.h>

/* sekiOS
 *
 * misc.c - miscellaneous doodads
 *
 */

volatile unsigned long long int timer_ticks = 0;	/* system time */

/* changes timer frequency: by default it's 18.2222hz.
 * some engineer at ibm was smoking something funky */
static void timer_phase (int hz)		/* change timer phase */
{
  int divisor = 1193180 / hz;	/* Calculate our divisor */
  outportb (0x43, 0x36);	/* Set command byte */
  outportb (0x40, divisor & 0xFF);	/* Set low byte of divisor */
  outportb (0x40, divisor >> 8);	/* Set high byte of divisor */
}

/* Handles the timer. In this case, it's very simple: We
*  increment the 'timer_ticks' variable every time the
*  timer fires. By default, the timer is set to fire at
*  18.2222hz, but we set it to 100hz for the sake of simplicity. */
void timer_handler (struct regs *r)
{ 

//  char buf[17];
  /* Increment our tick count */

  timer_ticks++;

  /*
  sprintf(buf, "%16x", timer_ticks);

  printxy((unsigned char *)buf, 80 - 16, 24); 
  */

}

/* Sets up the system clock by installing the timer handler
*  into IRQ0 */
void timer_install ()
{
  /* Installs 'timer_handler' to IRQ0  and sets timer tick to 100hz */
  timer_phase (TIMER_SPEED);
  irq_install_handler (0, timer_handler);
}

/* This will continuously loop until the given time has
*  been reached */
void timer_wait (unsigned long long ticks)
{
  unsigned long long eticks;

  eticks = timer_ticks + ticks;
  while (timer_ticks < eticks);
}
